package com.hudilao.service.impl;

import com.hudilao.dto.StockDTO;
import com.hudilao.entity.Dish;
import com.hudilao.entity.Stock;
import com.hudilao.entity.StockLog;
import com.hudilao.exception.OrderException;
import com.hudilao.mapper.StockLogMapper;
import com.hudilao.mapper.StockMapper;
import com.hudilao.service.DishService;
import com.hudilao.service.StockLogService;
import com.hudilao.service.StockService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * StockServiceImpl类，实现库存管理相关操作
 */
@Service
@Transactional
@Slf4j
public class StockServiceImpl extends ServiceImpl<StockMapper, Stock> implements StockService {

    @Autowired
    private DishService dishService;

    @Autowired
    private StockLogService stockLogService;

    @Autowired
    private StockService stockService;

    @Autowired
    private StockMapper stockMapper;

    //管理端：增加菜品库存
    @Override
    public void addStock(Long dishId, Integer quantity) {

        //根据菜品id查询到库存数据
        Stock stock = this.lambdaQuery().eq(Stock::getDishId, dishId).one();
        if (stock == null) {

            //如果库存为空则新建库存
            stock = new Stock();
            stock.setDishId(dishId);
            stock.setQuantity(quantity);

            //保存新建库存
            this.save(stock);
        } else {

            //如果库存存在，则增加菜品库存数量
            stock.setQuantity(stock.getQuantity() + quantity);

            //更新库存
            this.updateById(stock);
        }

        // 记录库存变动日志
        stockLogService.addStockLog(dishId, quantity);

        // 更新库存表的更新时间为最新的库存变动时间
        updateStockUpdateTime(dishId);
    }

//    //减少菜品库存
//    @Override
//    public void reduceStock(Long dishId, Integer quantity) {
//        Stock stock = this.lambdaQuery().eq(Stock::getDishId, dishId).one();
//        if (stock == null || stock.getQuantity() < quantity) {
//            throw new RuntimeException("库存不足");
//        }
//        stock.setQuantity(stock.getQuantity() - quantity);
//        this.updateById(stock);
//
//        // 记录库存变动日志
//        stockLogService.reduceStockLog(dishId, quantity);
//
//        // 更新库存表的更新时间为最新的库存变动时间
//        updateStockUpdateTime(dishId);
//    }

    //管理端：减少菜品库存
    @Override
    public void reduceStock(Long dishId, Integer quantity) {
        // 根据菜品id查询到库存数据
        Stock stock = this.lambdaQuery().eq(Stock::getDishId, dishId).one();

        if (stock != null) {
            // 减少菜品库存数量
            int newQuantity = stock.getQuantity() - quantity;

            if (newQuantity < 0) {
                throw new IllegalArgumentException("库存不足，无法减少库存");
            }

            stock.setQuantity(newQuantity);

            // 更新库存
            this.updateById(stock);

            // 记录库存变动日志（假设记录减少库存的日志）
            stockLogService.reduceStockLog(dishId, quantity);

            // 更新库存表的更新时间为最新的库存变动时间
            updateStockUpdateTime(dishId);
        } else {
            throw new IllegalArgumentException("菜品库存记录不存在");
        }
    }


    //管理端：库存分页查询
    @Override
    public Page<StockDTO> queryStock(int page, int pageSize, String dishName) {

        Page<Stock> stockPage = new Page<>(page, pageSize);
        LambdaQueryWrapper<Stock> queryWrapper = new LambdaQueryWrapper<>();

        //dishName不为空的情况下查询
        if (dishName != null && !dishName.isEmpty()) {
            List<Dish> dishes = dishService.lambdaQuery().like(Dish::getName, dishName).list();
            if (dishes != null && !dishes.isEmpty()) {
                queryWrapper.in(Stock::getDishId, dishes.stream().map(Dish::getId).toArray());
            } else {
                // 如果找不到对应的菜品，返回空结果
                return new Page<>();
            }
        }

        //构建排序条件，按照更新时间降序排序
        queryWrapper.orderByDesc(Stock::getUpdateTime);
        Page<Stock> resultPage = this.page(stockPage, queryWrapper);

        Page<StockDTO> stockDTOPage = new Page<>(page, pageSize);
        List<StockDTO> stockDTOList = resultPage.getRecords().stream().map(stock -> {

            //赋值属性
            StockDTO stockDTO = new StockDTO();
            stockDTO.setDishId(stock.getDishId());
            stockDTO.setQuantity(stock.getQuantity());
            stockDTO.setUpdateTime(stock.getUpdateTime()); // 使用库存表中的更新时间

            Dish dish = dishService.getById(stock.getDishId());
            if (dish != null) {
                stockDTO.setDishName(dish.getName());
            }
            return stockDTO;
        }).collect(Collectors.toList());

        //赋值records
        stockDTOPage.setRecords(stockDTOList);
        stockDTOPage.setTotal(resultPage.getTotal());
        return stockDTOPage;
    }

    /**管理端：
     * 更新库存表的更新时间为最新的库存变动时间
     * @param dishId 菜品ID
     */
    private void updateStockUpdateTime(Long dishId) {
        log.info("更新库存表时间，dishId: {}", dishId);

        // 根据 dishId 查询库存记录
        LambdaQueryWrapper<Stock> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Stock::getDishId, dishId);
        Stock existingStock = stockService.getOne(queryWrapper);

        //未找到库存记录，无法更新时间
        if (existingStock == null) {
            log.warn("未找到 dishId={} 对应的库存记录，无法更新", dishId);
            return;
        }

        // 更新库存记录的更新时间为最新的库存变动时间
        LocalDateTime latestUpdateTime = stockLogService.getLatestStockLogUpdateTime(dishId);
        existingStock.setUpdateTime(latestUpdateTime);

        // 执行更新操作
        boolean updateResult = stockService.updateById(existingStock);
        if (updateResult) {
            log.info("库存表更新时间成功");
        } else {
            log.error("库存表更新时间失败");
        }
    }


    //用户端

    /**
     * 顾客下单后更新库存
     * @param dishId
     * @param quantity
     */
    @Override
    public void reduceStockAfterOrder(Long dishId, Integer quantity) {
        //查询该菜品对应库存，如果不存在，抛出异常
        Stock stock = this.lambdaQuery().eq(Stock::getDishId,dishId).one();

        if(stock != null){
            //更新菜品库存
            int newQuantity = stock.getQuantity() - quantity;
            if(newQuantity < 0){
                throw new OrderException("库存不足");
            }

            stock.setQuantity(newQuantity);
            this.updateById(stock);
        }else{
            throw new OrderException("该菜品库存不存在，无法点单");
        }
    }

    /**
     * 根据菜品id获取库存
     * @param dishId 菜品id
     * @return 菜品库存
     */
    @Override
    public Integer getStockByDishId(long dishId) {
        return stockMapper.getStockByDishId(dishId);
    }
}
